package com.rainbow.config

import com.rainbow.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Component

@Component
class MyUserDetailsService : UserDetailsService {
    @Autowired
    lateinit var userService: UserService

    override fun loadUserByUsername(username: String): UserDetails {
        val user = userService.getByUsername(username) ?: throw UsernameNotFoundException("用户${username}不存在")

        val simpleGrantedAuthorities = createAuthorities(user.roles!!)

        return User(user.username, user.password, simpleGrantedAuthorities)

    }


    /**
     * 权限字符串转化
     *
     * 如 "USER,ADMIN" -> SimpleGrantedAuthority("USER") + SimpleGrantedAuthority("ADMIN")
     *
     * @param roleStr 权限字符串
     */
    fun createAuthorities(roleStr: String): List<SimpleGrantedAuthority> {

        val roles = roleStr.split(",")
        val simpleGrantedAuthorities = mutableListOf<SimpleGrantedAuthority>()
        for (role: String in roles) {
            simpleGrantedAuthorities.add(SimpleGrantedAuthority(role))
        }

        return simpleGrantedAuthorities
    }
}